package com.clone.surpassli.clone_cloudreader.ui.book.child;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.clone.surpassli.clone_cloudreader.MainActivity;
import com.clone.surpassli.clone_cloudreader.R;
import com.clone.surpassli.clone_cloudreader.adapter.BookAdapter;
import com.clone.surpassli.clone_cloudreader.base.BaseFragment;
import com.clone.surpassli.clone_cloudreader.bean.book.BookBean;
import com.clone.surpassli.clone_cloudreader.databinding.FragmentBookCustomBinding;
import com.clone.surpassli.clone_cloudreader.http.HttpClient;
import com.clone.surpassli.clone_cloudreader.utils.CommonUtils;
import com.clone.surpassli.clone_cloudreader.utils.DebugUtil;

import rx.Observer;
import rx.Scheduler;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by SurpassLi on 2017/10/11.
 * BookCustomFragment
 */

public class BookCustomFragment extends BaseFragment<FragmentBookCustomBinding> {
    private static final String TYPE = "param1";
    private String mType = "综合";
    private boolean mIsPrepared;
    private boolean mIsFirst = true;
    // 开始请求的角标
    private int mStart = 0;
    // 一次请求的数量
    private int mCount = 18;
    private MainActivity activity;
    private BookAdapter mBookAdapter;
    private GridLayoutManager mLayoutManager;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        activity = (MainActivity) context;
    }

    public static BookCustomFragment newInstance(String param1) {
        BookCustomFragment bookCustomFragment = new BookCustomFragment();
        Bundle args = new Bundle();
        args.putString(TYPE, param1);
        bookCustomFragment.setArguments(args);
        return bookCustomFragment;
    }

    @Override
    public int setContent() {
        return R.layout.fragment_book_custom;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mType = getArguments().getString(TYPE);
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        showContentView();
        bindingView.srlBookCustom.setColorSchemeColors(CommonUtils.getColor(R.color.colorTheme));
        bindingView.srlBookCustom.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                DebugUtil.error("----onRefresh");
                bindingView.srlBookCustom.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mStart = 0;
                        loadCustomData();
                    }
                }, 1000);
            }
        });

        mLayoutManager = new GridLayoutManager(getActivity(), 3);
        bindingView.rvBookCustom.setLayoutManager(mLayoutManager);

        scrollRecycleView();

        // 准备就绪
        mIsPrepared = true;
        /*
         * 因为启动时先走loadData()再走onActivityCreated，
         * 所以此处要额外调用load(),不然最初不会加载内容
         */
        loadData();
    }

    private void scrollRecycleView() {
        bindingView.rvBookCustom.addOnScrollListener(new RecyclerView.OnScrollListener() {
            int lastVisibleItem;
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();
                    if (mBookAdapter == null) {
                        return;
                    }
                    if (mLayoutManager.getItemCount() == 0) {
                        mBookAdapter.updateLoadStatus(BookAdapter.LOAD_NONE);
                        return;
                    }
                    if (lastVisibleItem + 1 == mLayoutManager.getItemCount()
                            && mBookAdapter.getLoadStatus() != BookAdapter.LOAD_MORE) {
                        mBookAdapter.updateLoadStatus(BookAdapter.LOAD_MORE);

                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mStart += mCount;
                                loadCustomData();
                            }
                        }, 1000);
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();
            }
        });
    }

    @Override
    protected void loadData() {
        DebugUtil.error("-----loadData");
        if (!mIsPrepared || !mIsVisible || !mIsFirst) {
            return;
        }
        bindingView.srlBookCustom.setRefreshing(true);
        bindingView.srlBookCustom.postDelayed(new Runnable() {
            @Override
            public void run() {
                loadCustomData();
            }
        }, 500);
        DebugUtil.error("-----setRefreshing");
    }

    /**
     * 网络获取数据
     */
    private void loadCustomData() {
        Subscription get = HttpClient.Builder.getDouBanService().getBook(mType, mStart, mCount)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BookBean>() {
                    @Override
                    public void onCompleted() {
                        showContentView();
                        if (bindingView.srlBookCustom.isRefreshing()) {
                            bindingView.srlBookCustom.setRefreshing(false);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        showContentView();
                        if (bindingView.srlBookCustom.isRefreshing()) {
                            bindingView.srlBookCustom.setRefreshing(false);
                            if (mStart == 0) {
                                showError();
                            }
                        }
                    }

                    @Override
                    public void onNext(BookBean bookBean) {
                        if (mStart == 0) {
                            if (bookBean != null && bookBean.getBooks() != null && bookBean.getBooks().size() > 0) {
                                if (mBookAdapter == null) {
                                    mBookAdapter = new BookAdapter(getActivity());
                                }
                                mBookAdapter.setList(bookBean.getBooks());
                                mBookAdapter.notifyDataSetChanged();
                                bindingView.rvBookCustom.setAdapter(mBookAdapter);
                            }
                            mIsFirst = false;
                        }else{
                            mBookAdapter.addAll(bookBean.getBooks());
                            mBookAdapter.notifyDataSetChanged();
                        }
                        if (mBookAdapter != null) {
                            mBookAdapter.updateLoadStatus(BookAdapter.LOAD_PULL_TO);
                        }
                    }
                });
        addSubscription(get);
    }

    @Override
    protected void onRefresh() {
        bindingView.srlBookCustom.setRefreshing(false);
        loadCustomData();
    }
}
